package org.sbbs.security.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.sbbs.base.service.impl.BaseTreeManagerImpl;
import org.sbbs.security.dao.MenuDao;
import org.sbbs.security.dao.UrlResourceDao;
import org.sbbs.security.model.Menu;
import org.sbbs.security.model.UrlResource;
import org.sbbs.security.service.MenuManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("menuManager")
public class MenuManagerImpl extends BaseTreeManagerImpl<Menu, Long> implements MenuManager {
	private MenuDao menuDao;
	private UrlResourceDao urlResourceDao;

	@Autowired
	public void setUrlResourceDao(UrlResourceDao urlResourceDao) {
		this.urlResourceDao = urlResourceDao;
	}

	@Autowired
	public MenuManagerImpl(MenuDao menuDao) {
		super(menuDao);
		this.menuDao = menuDao;
	}

	public void initMenuFromUrlResource() {
		Menu rm = this.getRootMenu();
		List ml = new ArrayList();

		List nsl = this.urlResourceDao.getDistinctNameSapces();

		for (Iterator iterator = nsl.iterator(); iterator.hasNext();) {
			String ns = (String) iterator.next();
			Menu m = new Menu();
			m.setParentNode(rm);
			m.setTitle(ns);
			m.setUrlResource(null);
			ml.add(m);
			List ll = this.urlResourceDao.getByNameSpace(ns);

			for (Iterator itr = ll.iterator(); itr.hasNext();) {
				UrlResource url = (UrlResource) itr.next();
				Menu mm = new Menu();
				mm.setParentNode(m);
				mm.setTitle(url.getName());
				mm.setUrlResource(url);
				ml.add(mm);
			}

		}
		this.menuDao.initMenu(ml);

	}

/*	@Override
	public void initMenuFromUrlResource(List urls) {
		Menu rm = this.getRootMenu();
		List ml = new ArrayList();

		for (Iterator iterator = urls.iterator(); iterator.hasNext();) {
			UrlResource url = (UrlResource) iterator.next();
			Menu m = new Menu();
			m.setParentNode(rm);
			m.setTitle(url.getName());
			m.setUrlResource(url);
			ml.add(m);
		}
		this.menuDao.initMenu(ml);
	}*/

	@Override
	public Menu getRootMenu() {
		List l = this.menuDao.getAllRoots();
		return (Menu) l.get(0);
	}

	@Override
	public void reBuildAllTree() {

		List rs = this.menuDao.getAllRoots();
		for (Iterator iterator = rs.iterator(); iterator.hasNext();) {
			Menu object = (Menu) iterator.next();
			this.menuDao.reBuildTree(object.getId(), object.getLft());
		}
		// this.menuDao.reBuildTree(arg0, arg1);

	}

}
